﻿#include "BaseType.h"
#include "Tracer.h"
#include "ComPort.h"
#include "Thread.h"

#include <stdlib.h>

#define COM_PORT	"/dev/ttySAC4"


ComPort* pCom=NULL;

class ComReciever:public Runnable{
public:
	void run()
	{
		sint32 ret;
		while(1)
		{
		    if (pCom!=NULL)
			{
			    char buf[64]={0};
        		ret=pCom->readData(buf, 63);
        		if(ret>0)
        		{
        			TRACE_DBG("COM recv:[%s]\n",buf);
        		}
        		else
        		{
        			TRACE_ERR("Com recv error,ret=%d\n",ret);
                    usleep(1000);
        		}
            }
			sleep(3);
		}

	}
};


void TestComPort()
{
	sint32 ret;
	Thread recvThread;
	ComReciever comRecv;
    
    pCom = NEW_OBJ ComPort();

    std::string inputStr;
    std::cout << "please input baud rate:" << std::endl;
    std::cin >> inputStr;
    std::cout << inputStr << std::endl;
	pCom->setAttribute(COM_ATTR_BAUDRATE, atoi(inputStr.c_str()));

    std::cout << "please input tty device:" << std::endl;
    std::cin >> inputStr;
    std::cout << inputStr << std::endl;
	ret=pCom->open(inputStr.c_str(), IO_MODE_RDWR_ONLY);
	if(STATUS_ERROR==ret)
	{
		TRACE_ERR("open %s error:%s\n", COM_PORT, ERROR_STRING);
		return;
	}
	recvThread.start(&comRecv);

    #define LIST_MAX       2
    const char* comandList[LIST_MAX]={
        "ATE0\r\n",
        "AT\r\n",
    };

	while(1)
	{
        for (int i=0; i<LIST_MAX; i++) 
        {
            TRACE_YELLOW("Send:[%s],len=%d\n",comandList[i], strlen(comandList[i]));
            ret=pCom->writeData(comandList[i], strlen(comandList[i]));
            if(ret<=0)
            {
                TRACE_ERR("Com send error,ret=%d\n",ret);
            }
            sleep(1);
        }
        sleep(3);
	}
}